﻿    using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using RastinArgham.CRM.Business;
using Mani.Common.WorkflowEngine;
using Mani.Common.Security;
using Shared;

namespace RastinArgham.CRM.Services
{
    public class CRMRobotWCF : ICRMRobotWCF
    {
        public ActivationInfo[] GetActivationUsernames()
        {
            try
            {
                CRMRepository repo = new CRMRepository();
                List<Order> orders = repo.GetServiceOrders(-1, 100, 1000, 0, true, false);
                orders.AddRange( repo.GetServiceOrders(-1, 104, 1000, 0, true, false) );

                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application");
                eventLog.Source = "CRMRobotWCF.GetActivationUsernames()";
                string usernames = String.Empty;

                foreach (var item in orders)
                    usernames += item.Contact.GetUsername() + ",";
                
                eventLog.WriteEntry("Getting list of activation usernames: " + usernames, System.Diagnostics.EventLogEntryType.Information);    

                return orders.Select(o => new ActivationInfo { OrderId = o.OrderId, Username = o.Contact.GetUsername(), OrderStateId = o.WorkflowStateId.Value}).ToArray();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application");
                eventLog.Source = "CRMRobotWCF.GetActivationUsernames()";
                eventLog.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
                return new List<ActivationInfo>().ToArray();
            }
        }

        public void UsernameActivationReport(int OrderId, string username, bool success, string reportMessage)
        {
            try
            {
                CRMRepository repo = new CRMRepository();
                aspnet_Users user = null;
                Order o = repo.GetOrderById(OrderId);
                WorkflowBasic wf = WorkflowFactory.Load(o.WorkflowInstanceId.Value);
                SecurityManager securityManager = new SecurityManager();
                user = securityManager.GetUserInfo("crm_robot");

                if (!success)
                {
                    RobotReport reportFailure = new RobotReport();
                    reportFailure.Report = reportMessage;
                    reportFailure.Success = false;
                    reportFailure.OrderId = OrderId;
                    reportFailure.Username = username;
                    reportFailure.Action = "ActivateUsername()";
                    reportFailure.ReportDate = DateTime.Now;
                    repo.AddReport(reportFailure);
                    repo.Save();

                    if ( o.WorkflowStateId == 100 )
                        wf.SendEventWithComment("WFEV__0100>0102", user.UserId, reportMessage);
                    else if ( o.WorkflowStateId == 104 )
                        wf.SendEventWithComment("WFEV__0104>0106", user.UserId, reportMessage);

                    return;
                }

                try
                {
                    RobotReport report = new RobotReport();

                    if (o.WorkflowStateId == 100)
                    {
                        wf.SendEvent("WFEV__0100>0104", user.UserId);
                        report.Report = "شناسه کاربری با موفقیت فعال شد";
                    }
                    else if (o.WorkflowStateId == 104)
                    {
                        wf.SendEvent("WFEV__0104>0110", user.UserId);
                        o.Activated = true;
                        report.Report = "تکمیل ثبت نام با موفقیت انجام شد ";
                    }

                    report.Success = true;
                    report.OrderId = OrderId;
                    report.Username = username;
                    report.Action = "ActivateUsername()";
                    report.ReportDate = DateTime.Now;
                    repo.AddReport(report);

                    repo.Save();
                }
                catch (Exception ex)
                {
                    RobotReport error = new RobotReport();

                    error.Report = ex.ToString();
                    error.Success = false;
                    error.OrderId = OrderId;
                    error.Username = username;
                    error.Action = "ActivateUsername()";
                    error.ReportDate = DateTime.Now;

                    repo.AddReport(error);
                    repo.Save();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application");
                eventLog.Source = "CRMRobotWCF.UsernameActivationReport()";
                eventLog.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }

        public void ContactRegistrationReport(int OrderId, string username, bool success, string reportMessage)
        {
            try
            {
                CRMRepository repo = new CRMRepository();

                if (!success && reportMessage != "این مشترک قبلا ثبت نام کرده است")
                {
                    RobotReport reportFailure = new RobotReport();
                    reportFailure.Report = reportMessage;
                    reportFailure.Success = false;
                    reportFailure.OrderId = OrderId;
                    reportFailure.Username = username;
                    reportFailure.Action = "ContactsRegistration()";
                    reportFailure.ReportDate = DateTime.Now;
                    repo.AddReport(reportFailure);
                    repo.Save();

                    Order o = repo.GetOrderById(OrderId);
                    WorkflowBasic wf = WorkflowFactory.Load(o.WorkflowInstanceId.Value);
                    SecurityManager securityManager = new SecurityManager();
                    aspnet_Users user = securityManager.GetUserInfo("crm_robot");
                    if (o.WorkflowStateId == 87)
                    {
                        wf.SendEventWithComment("WFEV__0087>0088", user.UserId, reportMessage);
                    }
                    else if (o.WorkflowStateId == 100)
                    {
                        wf.SendEventWithComment("WFEV__0100>0088", user.UserId, reportMessage);
                    }
                    return;
                }

                try
                {
                    SuccessfullRegistration(OrderId, username, reportMessage);
                }
                catch (Exception ex)
                {
                    RobotReport error = new RobotReport();
                    error.Report = ex.ToString();
                    error.Success = false;
                    error.OrderId = OrderId;
                    error.Username = username;
                    error.Action = "ContactsRegistration()";
                    error.ReportDate = DateTime.Now;
                    repo.AddReport(error);
                    repo.Save();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application");
                eventLog.Source = "CRMRobotWCF.ContactRegistrationReport()";
                eventLog.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }

        private void SuccessfullRegistration(int OrderId, string username, string reportMessage)
        {
            CRMRepository repo = new CRMRepository();
            Order o = repo.GetOrderById(OrderId);

            if (o.WorkflowStateId == 87)
            {
                WorkflowBasic wf = WorkflowFactory.Load(o.WorkflowInstanceId.Value);
                SecurityManager securityManager = new SecurityManager();
                aspnet_Users user = securityManager.GetUserInfo("crm_robot");
                wf.SendEvent("WFEV__0087>0090", user.UserId);
            }

            RobotReport report = new RobotReport();
            if (reportMessage == "این مشترک قبلا ثبت نام کرده است")
                report.Report = reportMessage;
            else
                report.Report = "کاربر با موفقیت ثبت نام شد";

            report.Success = true;
            report.OrderId = OrderId;
            report.Username = username;
            report.Action = "ContactsRegistration()";
            report.ReportDate = DateTime.Now;
            repo.AddReport(report);

            o.Registered = true;
            repo.Save();
        }

        public MobinContact[] GetRegistrationContacts()
        {
            try
            {
                CRMRepository repo = new CRMRepository();
                List<MobinContact> contacts = new List<MobinContact>();

                List<Order> personalOrders = repo.GetServiceOrders(-1, 100, 1000, 0, ContactTypes.Personal, false, false);
                personalOrders.AddRange( repo.GetServiceOrders(-1, 87, 1000, 0, ContactTypes.Personal, false, false) );

                List<Order> companyOrders = repo.GetServiceOrders(-1, 100, 1000, 0, ContactTypes.Company, false, false);
                companyOrders.AddRange( repo.GetServiceOrders(-1, 87, 1000, 0, ContactTypes.Company, false, false));

                // Adding Personal Contacts
                contacts.AddRange( personalOrders.Select(o => new MobinContact
                {
                    OrderId = o.OrderId,
                    AcademicDegree = 3,
                    Address = o.Contact.Address,
                    Birthday = o.Contact.PersonalContacts.FirstOrDefault().Birthday.Value,
                    CityId = o.Contact.City.MobinCityId.Value,
                    EducationalMajor = o.Contact.PersonalContacts.FirstOrDefault().EducationalMajor,
                    Email = o.Contact.Email,
                    FatherName = o.Contact.PersonalContacts.FirstOrDefault().FatherName,
                    Fax = o.Contact.Fax,
                    HighSpeed = false,
                    IdentityIssuePlace = o.Contact.PersonalContacts.FirstOrDefault().IdentityIssuePlace,
                    IdentityNumber = o.Contact.PersonalContacts.FirstOrDefault().IdentityNumber,
                    InstallationAddress = o.InstallationInformations.FirstOrDefault().Address,
                    InstallationBuildingName = o.InstallationInformations.FirstOrDefault().BuildingName,
                    InstallationCityId = o.InstallationInformations.FirstOrDefault().City.MobinCityId.Value,
                    InstallationFloor = o.InstallationInformations.FirstOrDefault().Floor,
                    InstallationPlaque = o.InstallationInformations.FirstOrDefault().Plaque,
                    InstallationProvinceId = o.InstallationInformations.FirstOrDefault().City.Province.MobinProvinceId.Value,
                    InstallationRegion = o.InstallationInformations.FirstOrDefault().Region,
                    InstallationVahed = o.InstallationInformations.FirstOrDefault().UnitNumber,
                    Job = o.Contact.PersonalContacts.FirstOrDefault().Job,
                    Mobile = o.Contact.MobilePhone,
                    NationalCode = o.Contact.PersonalContacts.FirstOrDefault().NationalCode,
                    PersonalEnglishFullName = o.Contact.FullContactTitle,
                    PersonalFirstName = o.Contact.PersonalContacts.FirstOrDefault().FirstName,
                    PersonalLastName = o.Contact.PersonalContacts.FirstOrDefault().LastName,
                    ProductTitle = o.Service.MobinServiceName,
                    ProvinceId = o.Contact.City.Province.MobinProvinceId.Value,
                    RequestType = 1,
                    ServiceDuration = o.Quantity.Value,
                    Tel = o.Contact.Phone,
                    Username = o.Contact.GetUsername(),
                    WebSite = o.Contact.Website,
                    ZipCode = o.Contact.ZipCode
                }).ToList());


                // Adding Company Contacts
                contacts.AddRange(companyOrders.Select(o => new MobinContact
                {
                    OrderId = o.OrderId,
                    Address = o.Contact.Address,
                    CityId = o.Contact.City.MobinCityId.Value,
                    Email = o.Contact.Email,
                    Fax = o.Contact.Fax,
                    HighSpeed = true,
                    InstallationAddress = o.InstallationInformations.FirstOrDefault().Address,
                    InstallationBuildingName = o.InstallationInformations.FirstOrDefault().BuildingName,
                    InstallationCityId = o.InstallationInformations.FirstOrDefault().City.MobinCityId.Value,
                    InstallationFloor = o.InstallationInformations.FirstOrDefault().Floor,
                    InstallationPlaque = o.InstallationInformations.FirstOrDefault().Plaque,
                    InstallationProvinceId = o.InstallationInformations.FirstOrDefault().City.Province.MobinProvinceId.Value,
                    InstallationRegion = o.InstallationInformations.FirstOrDefault().Region,
                    InstallationVahed = o.InstallationInformations.FirstOrDefault().UnitNumber,
                    Mobile = o.Contact.MobilePhone,
                    ProductTitle = o.Service.MobinServiceName,
                    ProvinceId = o.Contact.City.Province.MobinProvinceId.Value,
                    RequestType = 2,
                    ServiceDuration = o.Quantity.Value,
                    Tel = o.Contact.Phone,
                    Username = o.Contact.GetUsername(),
                    WebSite = o.Contact.Website,
                    ZipCode = o.Contact.ZipCode,
                    CompanyActivityField = o.Contact.CompanyContacts.FirstOrDefault().CompanyActivityField,
                    CompanyEnglishName = o.Contact.FullContactTitle,
                    CompanyName = o.Contact.CompanyContacts.FirstOrDefault().CompanyName,
                    Economics = "-",
                    ManagerAcademicDegree = 3,
                    ManagerBirthday = o.Contact.CompanyContacts.FirstOrDefault().ManagerBirthday.Value,
                    ManagerEducationalMajor = o.Contact.CompanyContacts.FirstOrDefault().ManagerEducationalMajor,
                    ManagerEnglishFullName = o.Contact.CompanyContacts.FirstOrDefault().ManagerFullNameEnglish,
                    ManagerFirstName = o.Contact.CompanyContacts.FirstOrDefault().ManagerFirstName,
                    ManagerLastName = o.Contact.CompanyContacts.FirstOrDefault().ManagerLastName,
                    ManagerNationalCode = o.Contact.CompanyContacts.FirstOrDefault().ManagerNationalCode,
                    RegistrationNumber = o.Contact.CompanyContacts.FirstOrDefault().RegistrationNumber
                }).ToList());


                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application");
                eventLog.Source = "CRMRobotWCF.GetRegistrationContacts()";
                string usernames = String.Empty;

                foreach (var item in contacts)
                    usernames += item.Username + ",";

                eventLog.WriteEntry("Getting list of registration usernames: " + usernames, System.Diagnostics.EventLogEntryType.Information);


                return contacts.ToArray();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog("Application");
                eventLog.Source = "CRMRobotWCF.GetRegistrationContacts()";
                eventLog.WriteEntry(ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
                return new List<MobinContact>().ToArray();
            }
        }

        public MobinContact[] GetRegistrationContactsMock()
        {
            MobinContact[] contacts = new MobinContact[4];
            contacts[0] = new MobinContact { Username = "123" };
            contacts[1] = new MobinContact { Username = "123" };
            contacts[2] = new MobinContact { Username = "123" };
            contacts[3] = new MobinContact { Username = "123" };
            return contacts;
        }
    }
}
